package com.sgai.zero_robot.ui.config;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.sgai.zero_robot.R;
import com.sgai.zero_robot.base.BaseActivity;
import com.sgai.zero_robot.base.BaseViewModel;
import com.sgai.zero_robot.databinding.ActivityConfigBinding;
import com.sgai.zero_robot.pojo.Province;
import com.sgai.zero_robot.ui.control.ZeroControlActivity;
import com.sgai.zero_robot.ui.select_file_config.SelectFileConfigActivity;
import com.sgai.zero_robot.utils.LogUtil;
import com.sgai.zero_robot.utils.ThreadPoolUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class ConfigActivity extends BaseActivity<ActivityConfigBinding, BaseViewModel> implements View.OnClickListener {
    private static List<Province> provinces;
    private final String[] installArray = {"小号侧", "大号侧"};
    private final String[] phaseArray = {"A相", "B相", "C相"};
    private final String[] insulatorNumArray = {"单串", "双串", "三串"};
    private final String[] numOneArray = {"中串"};
    private final String[] numTwoArray = {"外串", "内串"};
    private final String[] numThreeArray = {"外串", "中串", "内串"};
    private final String[] directionArray = {"高压侧", "杆塔侧"};
    private int province;
    private int city;
    private String lineName;
    private String towerNum;
    private int install = 1;
    private int phase = 1;
    private int insulatorNum = 1;

    private int insulator = 2;
    private int direction = 1;

    @Override
    protected boolean isWindowChange() {
        return false;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                .navigationBarAlpha(0f)  //导航栏透明度，不写默认0.0F
                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
                .fullScreen(true)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)  //单独指定软键盘模式
//                .addTag("tag")  //给以上设置的参数打标记
//                .getTag("tag")  //根据tag获得沉浸式参数
//                .reset()  //重置所以沉浸式参数
                .init();  //必须调用方可应用以上所配置的参数
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        initSpinnar();
        mBinding.btSubmit.setOnClickListener(this);
        mBinding.ivCallback.setOnClickListener(this);
        mBinding.ivImportExcel.setOnClickListener(this);
    }
    @Override
    public void loadData() {

    }
    @Override
    public void onClick(View v) {
        if (v == mBinding.btSubmit){
            lineName = mBinding.etLineName.getText().toString();
            if (TextUtils.isEmpty(lineName)) {
                showAlarm(2,"警告","请输入线路名称",null);
                return;
            }
            towerNum = mBinding.etTowerNum.getText().toString();
            if (TextUtils.isEmpty(towerNum)) {
                showAlarm(2,"警告","请输入杆塔号",null);
                return;
            }
            Province province1 = provinces.get(province);
            String provinceName = province1.getName();
            String cityName = province1.getCities().get(city);
            Intent intent = new Intent(this, ZeroControlActivity.class);
            intent.putExtra("provinceName",provinceName);
            intent.putExtra("cityName",cityName);
            intent.putExtra("lineName",lineName);
            intent.putExtra("towerNum",towerNum);
            intent.putExtra("install",install);
            intent.putExtra("phase",phase);
            intent.putExtra("insulatorNum",insulatorNum);
            intent.putExtra("insulator",insulator);
            intent.putExtra("direction",direction);
            LogUtil.e(TAG,"provinceName="+provinceName);
            LogUtil.e(TAG,"cityName="+cityName);
            LogUtil.e(TAG,"lineName="+lineName);
            LogUtil.e(TAG,"towerNum="+towerNum);
            LogUtil.e(TAG,"install="+install);
            LogUtil.e(TAG,"phase="+phase);
            LogUtil.e(TAG,"insulatorNum="+insulatorNum);
            LogUtil.e(TAG,"insulator="+insulator);
            LogUtil.e(TAG,"direction="+direction);
            startActivity(intent);
            finish();

        }else if (v == mBinding.ivCallback){
            finish();
        }else if (v == mBinding.ivImportExcel){
            startActivityForResult(new Intent(this, SelectFileConfigActivity.class),1100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1100&&resultCode == RESULT_OK){
            if (data!=null){
                String province1 = data.getStringExtra("province");
                String city1 = data.getStringExtra("city");
                String lineName1 = data.getStringExtra("lineName");
                int towerNum1 = data.getIntExtra("towerNum",0);
                for (int i =0;i<provinces.size();i++){
                    if (province1.equals(provinces.get(i).getName())){
                        province = i;
                        mBinding.sProvince.setSelection(i);
                        List<String> cities = provinces.get(province).getCities();
                        ArrayAdapter<String> cityAdapter =
                                new ArrayAdapter<>(ConfigActivity.this, R.layout.spinner_item, cities);
                        cityAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
                        mBinding.sCity.setAdapter(cityAdapter);
                        for (int j = 0;j<cities.size();j++){
                            if (city1.equals(cities.get(j))){
                                city = j;
                                mBinding.sCity.setSelection(j);
                                break;
                            }
                        }
                        break;
                    }
                }
                if (!TextUtils.isEmpty(lineName1)){
                    mBinding.etLineName.setText(lineName1);
                }
                if (towerNum1>0){
                    mBinding.etTowerNum.setText("#"+towerNum1);
                }

            }
        }
    }

    private void initSpinnar() {
        setSpinnarAdapter(mBinding.sInstall, installArray);
        setSpinnarAdapter(mBinding.sPhase, phaseArray);
        setSpinnarAdapter(mBinding.sNum, insulatorNumArray);
        setSpinnarAdapter(mBinding.sPoint, numOneArray);
        setSpinnarAdapter(mBinding.sDirection, directionArray);
        if (provinces == null) {
            readJsonFromAssets(new ReadCallback() {
                @Override
                public void onResult(List<Province> list) {
                    provinces = list;
                    // 2. 省份 Spinner 绑定
                    String[] provinceNames = new String[provinces.size()];
                    for (int i = 0; i < provinces.size(); i++) {
                        provinceNames[i] = provinces.get(i).getName();
                    }
                    setSpinnarAdapter(mBinding.sProvince, provinceNames);
                    // 3. 初始化城市 Spinner（默认第 0 个省）
                    updateCitySpinner(0);
                }
            });
        } else {
            String[] provinceNames = new String[provinces.size()];
            for (int i = 0; i < provinces.size(); i++) {
                provinceNames[i] = provinces.get(i).getName();
            }
            setSpinnarAdapter(mBinding.sProvince, provinceNames);
            // 3. 初始化城市 Spinner（默认第 0 个省）
            updateCitySpinner(0);
        }

        mBinding.sProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateCitySpinner(position);
                if (position !=province){
                    province = position;
                    city = 0;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        mBinding.sCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position !=city){
                    city = position;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mBinding.sInstall.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                install = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mBinding.sPhase.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                phase = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mBinding.sNum.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                insulatorNum = position + 1;
                if (insulatorNum == 1) {
                    //如果是单串 意思就只有中串
                    insulator = 2;
                    setSpinnarAdapter(mBinding.sPoint, numOneArray);
                } else if (insulatorNum == 2) {
                    //如果是双串  就是内串和外串
                    setSpinnarAdapter(mBinding.sPoint, numTwoArray);
                    insulator = 1;
                } else {
                    setSpinnarAdapter(mBinding.sPoint, numThreeArray);
                    insulator = 1;
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        mBinding.sPoint.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (insulatorNum == 1) {
                    insulator = 2;
                } else if (insulatorNum == 2) {
                    if (i == 0) {
                        insulator = 1;
                    } else if (i == 1) {
                        insulator = 3;
                    }
                } else {
                    insulator = i + 1;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
        mBinding.sDirection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                direction = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    private void setSpinnarAdapter(Spinner spinnar, String[] content) {
        ArrayAdapter<String> provinceAdapter = new ArrayAdapter<>(ConfigActivity.this, R.layout.spinner_item, content);
        provinceAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        spinnar.setAdapter(provinceAdapter);
        spinnar.setPrompt("请选择");
    }

    /**
     * 从 assets 文件中读取 JSON
     */
    private void readJsonFromAssets(ReadCallback readCallback) {
        showLoading("正在加载...");
        ThreadPoolUtils.getInstance().addParallelTask(new Runnable() {
            @Override
            public void run() {
                StringBuilder builder = new StringBuilder();
                try (BufferedReader reader =
                             new BufferedReader(new InputStreamReader(getAssets().open("province_city.json")))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(builder)) {
                    return;
                }
                List<Province> list = Arrays.asList(new Gson().fromJson(builder.toString(), Province[].class));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoading();
                        if (readCallback != null) {
                            readCallback.onResult(list);
                        }
                    }
                });

            }
        });

        return;
    }

    /**
     * 更新城市下拉框
     */
    private void updateCitySpinner(int provinceIndex) {
        List<String> cities = provinces.get(provinceIndex).getCities();
        ArrayAdapter<String> cityAdapter =
                new ArrayAdapter<>(ConfigActivity.this, R.layout.spinner_item, cities);
        cityAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        mBinding.sCity.setAdapter(cityAdapter);
    }

}